package com.kuaifawu.lwnlawyerclient.Fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Activity.LWNLoginActivity;
import com.kuaifawu.lwnlawyerclient.Adapter.DrawerListAdapter;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.DrawerListItem;
import com.kuaifawu.lwnlawyerclient.Lib.LWNDataLoader;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_lawyerInfo;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class NavigationDrawerFragment extends Fragment {
    /**
     * 存放选中item的位置
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * 存放用户是否需要默认开启drawer的key
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * 宿主activity实现的回调接口的引用
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * 将action bar和drawerlayout绑定的组件
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    public ListView mDrawerListView;
    private View mFragmentContainerView;
    private View headerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;
    private List<DrawerListItem> mData = new ArrayList<DrawerListItem>();
    public NavigationDrawerFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通过这个flag判断用户是否已经知道drawer了，第一次启动应用显示出drawer（抽屉），之后启动应用默认将其隐藏
//        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
//        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
//
//        if (savedInstanceState != null) {
//            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
//            mFromSavedInstanceState = true;
//        }

        registerBoradcastReceiver();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 设置该fragment拥有自己的actionbar action item
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

        LWNModel_lawyerInfo model_lawyerInfo = LWNModel_lawyerInfo.getInstance();
        headerView = inflater.inflate(R.layout.list_header,mDrawerListView,false);
        LWNDataLoader.LoadHeadView(headerView,model_lawyerInfo);

        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallbacks.onNavigationDrawerItemSelected("个人中心");
                mDrawerListView.setItemChecked(0, true);
                mDrawerLayout.closeDrawer(mFragmentContainerView);
            }
        });

        mDrawerListView.addHeaderView(headerView);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });

        String[] itemTitle = getResources().getStringArray(R.array.item_title);
        int[] itemIconRes = {
                R.drawable.background_mainlist_home,
                R.drawable.background_mainlist_myquestion,
                R.drawable.background_mainlist_chengzhang,
                R.drawable.background_mainlist_feedback,
                R.drawable.background_mainlist_systemset,
                R.drawable.background_mainlist_saosao,
        };


        for (int i = 0; i < itemTitle.length; i++) {
            DrawerListItem item = new DrawerListItem(getResources().getDrawable(itemIconRes[i]), itemTitle[i]);
            mData.add(item);
        }

        selectItem(mCurrentSelectedPosition);
        DrawerListAdapter adapter = new DrawerListAdapter(this.getActivity(), mData);
        mDrawerListView.setAdapter(adapter);
        mDrawerListView.setItemChecked(1, true);
        return mDrawerListView;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * 设置导航drawer
     *
     * @param fragmentId   fragmentent的id
     * @param drawerLayout fragment的容器
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        //隐藏Action bar上的app icon
        //actionBar.setDisplayShowHomeEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* 宿主 */
                mDrawerLayout,                    /* DrawerLayout 对象 */
                R.drawable.ic_drawer,             /* 替换actionbar上的'Up'图标 */
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().supportInvalidateOptionsMenu(); // 调用 onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
                }

                getActivity().supportInvalidateOptionsMenu(); // 调用 onPrepareOptionsMenu()

                LWNModel_lawyerInfo model_lawyerInfo = LWNModel_lawyerInfo.getInstance();
                LWNDataLoader.reloadHeadView(headerView,model_lawyerInfo);
            }
        };

        // 如果是第一次进入应用，显示抽屉
//        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
//            mDrawerLayout.openDrawer(mFragmentContainerView);
//        }

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private void selectItem(int position) {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }

        if(position == 0){
            String token = LWNModel_user.getInstance().getString_token(getActivity());
            if(token == null) {
            /* 新建一个Intent对象 */
                Intent intent = new Intent();
            /* 指定intent要启动的类 */
                intent.setClass(getActivity(), LWNLoginActivity.class);
            /* 启动一个新的Activity */
                this.startActivityForResult(intent,300);
               getActivity().finish();
            }
        }

        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
        	if(mCurrentSelectedPosition == 0) {
        		mCallbacks.onNavigationDrawerItemSelected(getString(R.string.app_title));
        		return;
        	}
            mCallbacks.onNavigationDrawerItemSelected(mData.get(position - 1).getTitle());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 300:{

            }break;
            default:{

            }break;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 当系统配置改变时调用DrawerToggle的改变配置方法（例如横竖屏切换会回调此方法）
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //当抽屉打开时显示应用全局的actionbar设置
        if (mDrawerLayout != null && isDrawerOpen()) {
            //inflater.inflate(R.menu.global, menu);
            showGlobalContextActionBar();

        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        if (item.getItemId() == R.id.action_myQuestion) {
            //Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 当抽屉打开时显示应用全局的actionbar设置
     */
    private void showGlobalContextActionBar() {
//        ActionBar actionBar = getActionBar();
//        actionBar.setDisplayShowTitleEnabled(true);
//        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
//        actionBar.setTitle(R.string.app_title);
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    /**
     * 宿主activity要实现的回调接口
     * 用于activity与该fragment之间通讯
     */
    public static interface NavigationDrawerCallbacks {
        /**
         * 当drawer中的某个item被选择是调用该方法
         */
        void onNavigationDrawerItemSelected(String title);
    }

    public void getLawyerInfoFromNetwork() {
        final ProgressDialog proDialog = android.app.ProgressDialog.show(getActivity(), "", getResources().getString(R.string.toast_wait));
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        String string_url = center.getInstance().getLawyerInfo(getActivity());
        //System.out.println(string_url);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");

                            switch (Integer.parseInt(string_code)) {
                                case 10000: {
                                    JSONObject json_object = jsonObject.getJSONObject("data");

                                }
                                break;
                                case 10001: {
                                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                                case 10003: {
                                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                                default: {
                                    Toast toast = Toast.makeText(getActivity().getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getActivity().getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }

    //注册广播
    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(getResources().getString(R.string.broadcast_loginOut));
        //注册广播
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    //接收退登刷新
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(getResources().getString(R.string.broadcast_loginOut))){
               selectItem(0);
            }
        }

    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }
}
